import { EnumChatMessageType, EnumMyChatEventType, EnumSender, type MyChatConversationResult, type MyChatEventResult } from "@/api/siderBar/model"
import { getMychatChatdetailId, getMychatPreconnect, postMychatInvalidId, postMychatReadmsgId, postMychatSendmobieId, postMychatSendmsgId, postMychatSendresumeId, postMychatSendwechatId } from "@/api/siderBar/myChat"
import { useAppStore } from "@/stores"
import { message, Modal } from "ant-design-vue"
import { useChatMessages } from "./useChatMessages"

enum ActionType {
    SWAP_RESUME,
    SWAP_MOBILE,
    SWAP_WECAHT,
}
export function useChatRoom() {
    const appStore = useAppStore()
    const actions: IOption<ActionType>[] = [
        { value: ActionType.SWAP_RESUME, label: '求简历' },
        { value: ActionType.SWAP_MOBILE, label: '换手机' },
        { value: ActionType.SWAP_WECAHT, label: '换微信' }
    ]
    const content = ref("")
    const withAI = ref(false)
    const currentSesion = ref<number>()
    const {
        messages,
        scrollEl,
        fetchMessageList,
        getNextMessage,
        appendCustomeMessage,
        scrollToLast,
        handleMessageAnyEvent
    } = useChatMessages(currentSesion)
    const chatDetail = ref<INullable<MyChatConversationResult>>(null)
    const { data: wsInfo } = useRequest(getMychatPreconnect, {
        cacheKey: "getMychatPreconnect",
        staleTime: 60000,
    })
    const wsUrl = computed(() => wsInfo.value?.server)
    const { close } = useWebSocket(wsUrl, {
        onConnected() {
            console.log("%cws连接成功", "color: green; font-size: 24px;")
        },
        onDisconnected() {
            console.log("%cws已断开连接", "color: pink; font-size: 24px;")
        },
        onError(_, event) {
            console.log("%cws发生错误", "color: red; font-size: 24px;")
            console.error(event)
        },
        onMessage(_, {data}) {
            console.log("%c收到消息", "color: skyblue; font-size: 24px;")
            console.log(typeof data === "string" ? JSON.parse(data) : data)
            const incomingData = <MyChatEventResult>JSON.parse(data)
            if (incomingData.type === EnumMyChatEventType.聊天消息) {
                getNextMessage(incomingData.id!)
            }
        }
    })
    onBeforeUnmount(() => {
        close()
    })
    function toggleCurrentSesion(session: number) {
        if (currentSesion.value === session) return
        currentSesion.value = session
        getChatDetail()
        fetchMessageList(true)
    }
    async function getChatDetail() {
        if (!currentSesion.value) return
        appStore.toggleLoading(true)
        chatDetail.value = await getMychatChatdetailId(currentSesion.value)
        if (chatDetail.value.unreadCount) {
            await postMychatReadmsgId(currentSesion.value)
            chatDetail.value.unreadCount = 0
        }
        appStore.toggleLoading(false)
    }
    function markUnfit() {
        if (!currentSesion.value) return
        Modal.confirm({
            title: "确认提示",
            content: "确认要标记为不合适？",
            onOk() {
                return postMychatInvalidId(currentSesion.value!).then(() => {
                    message.success("已标记不合适")
                })
            }
        })
    }
    async function handleAction(action: IOption<ActionType>) {
        const sessionId = toValue(currentSesion)
        if (!sessionId) return
        if (action.value === ActionType.SWAP_RESUME) {
            const nextMessageId = await postMychatSendresumeId(sessionId)
            nextMessageId && await getNextMessage(nextMessageId)
        } else if (action.value === ActionType.SWAP_MOBILE) {
            const nextMessageId = await postMychatSendmobieId(sessionId)
            nextMessageId && await getNextMessage(nextMessageId)
        } else if (action.value === ActionType.SWAP_WECAHT) {
            const nextMessageId = await postMychatSendwechatId(sessionId)
            nextMessageId && await getNextMessage(nextMessageId)
        }
        message.success("操作成功")
    }
    async function sendMessage() {
        const sessionId = currentSesion.value
        if (!sessionId) return
        const message = toValue(content).trim()
        if (!message) return
        await postMychatSendmsgId(sessionId, {
            content: message,
            type: EnumChatMessageType.文本
        })
        content.value = ""
        appendCustomeMessage({
            sender: EnumSender.HR,
            type: EnumChatMessageType.文本,
            content: message,
        })
        scrollToLast()
    }
    return {
        actions,
        content,
        withAI,
        currentSesion,
        toggleCurrentSesion,
        chatDetail,
        getChatDetail,
        markUnfit,
        handleAction,
        sendMessage,
        messages,
        scrollEl,
        handleMessageAnyEvent,
        getNextMessage
    }
}